<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 页面头部 -->
    <page-header 
      title="高级SEO设置" 
      subtitle="配置网站的高级SEO选项，包括结构化数据、元标签模板等"
    >
      <template #extra>
        <button 
          class="btn btn-primary"
          @click="handleSave"
          :loading="saving"
        >
          <i v-if="saving" class="fa fa-spinner fa-spin mr-1"></i>
          保存设置
        </button>
      </template>
    </page-header>
    
    <!-- 主要内容区 -->
    <div class="px-4 sm:px-6 lg:px-8 py-6">
      <!-- 配置选项卡 -->
      <div class="mb-6 border-b border-gray-200">
        <nav class="-mb-px flex" aria-label="Tabs">
          <button
            v-for="tab in tabs"
            :key="tab.id"
            :class="['py-4 px-1 border-b-2 text-sm font-medium', 
              activeTab === tab.id 
                ? 'border-primary text-primary' 
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300']"
            @click="activeTab = tab.id"
          >
            {{ tab.name }}
          </button>
        </nav>
      </div>
      
      <div class="bg-white rounded-lg shadow-md p-6 max-w-4xl mx-auto">
        <!-- 结构化数据设置 -->
        <div v-if="activeTab === 'structured-data'">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">结构化数据设置</h3>
          <p class="text-sm text-gray-600 mb-6">
            配置网站的结构化数据（Schema.org），帮助搜索引擎更好地理解网站内容，可能获得更丰富的搜索结果展示。
          </p>
          
          <div class="space-y-6">
            <!-- 启用结构化数据 -->
            <div>
              <label class="inline-flex items-center">
                <input
                  type="checkbox"
                  v-model="advancedSeoForm.structuredData.enabled"
                  class="text-primary focus:ring-primary"
                >
                <span class="ml-2 text-sm font-medium text-gray-700">启用结构化数据标记</span>
              </label>
            </div>
            
            <!-- 网站类型 -->
            <div v-if="advancedSeoForm.structuredData.enabled" class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-1">
                网站类型
                <span class="text-red-500">*</span>
              </label>
              <select
                v-model="advancedSeoForm.structuredData.siteType"
                class="form-input w-full"
                :disabled="!advancedSeoForm.structuredData.enabled"
              >
                <option value="Website">通用网站 (Website)</option>
                <option value="Blog">博客 (Blog)</option>
                <option value="Ecommerce">电子商务 (E-commerce)</option>
                <option value="NewsArticle">新闻网站 (NewsArticle)</option>
                <option value="Organization">组织 (Organization)</option>
              </select>
            </div>
            
            <!-- 组织信息 -->
            <div 
              v-if="advancedSeoForm.structuredData.enabled && 
                   advancedSeoForm.structuredData.siteType === 'Organization'"
              class="p-4 bg-gray-50 rounded-md border border-gray-200"
            >
              <h4 class="font-medium text-gray-800 mb-3">组织信息</h4>
              
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">组织名称</label>
                  <input
                    type="text"
                    v-model="advancedSeoForm.structuredData.organization.name"
                    placeholder="输入组织名称"
                    class="form-input w-full"
                  >
                </div>
                
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">组织Logo URL</label>
                  <input
                    type="url"
                    v-model="advancedSeoForm.structuredData.organization.logo"
                    placeholder="https://example.com/logo.png"
                    class="form-input w-full"
                  >
                </div>
                
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">联系电话</label>
                  <input
                    type="tel"
                    v-model="advancedSeoForm.structuredData.organization.phone"
                    placeholder="输入联系电话"
                    class="form-input w-full"
                  >
                </div>
                
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">联系邮箱</label>
                  <input
                    type="email"
                    v-model="advancedSeoForm.structuredData.organization.email"
                    placeholder="contact@example.com"
                    class="form-input w-full"
                  >
                </div>
              </div>
            </div>
            
            <!-- 结构化数据预览 -->
            <div v-if="advancedSeoForm.structuredData.enabled" class="mt-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                结构化数据预览
              </label>
              <pre class="bg-gray-800 text-gray-100 p-4 rounded-md text-xs overflow-x-auto max-h-60">
{{ structuredDataPreview }}</pre>
            </div>
          </div>
        </div>
        
        <!-- 页面元标签模板 -->
        <div v-if="activeTab === 'meta-templates'">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">页面元标签模板</h3>
          <p class="text-sm text-gray-600 mb-6">
            为不同类型的页面配置元标签模板，支持变量替换（如{title}、{category}等）。
          </p>
          
          <div class="space-y-6">
            <!-- 首页模板 -->
            <div class="p-4 bg-gray-50 rounded-md border border-gray-200">
              <h4 class="font-medium text-gray-800 mb-3">首页</h4>
              
              <div class="space-y-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    Meta 标题模板
                  </label>
                  <input
                    type="text"
                    v-model="advancedSeoForm.metaTemplates.home.title"
                    placeholder="例如：{siteTitle} - 首页"
                    class="form-input w-full"
                  >
                </div>
                
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    Meta 描述模板
                  </label>
                  <textarea
                    v-model="advancedSeoForm.metaTemplates.home.description"
                    class="form-input w-full min-h-[80px]"
                  ></textarea>
                </div>
              </div>
            </div>
            
            <!-- 文章页模板 -->
            <div class="p-4 bg-gray-50 rounded-md border border-gray-200">
              <h4 class="font-medium text-gray-800 mb-3">文章页</h4>
              
              <div class="space-y-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    Meta 标题模板
                  </label>
                  <input
                    type="text"
                    v-model="advancedSeoForm.metaTemplates.article.title"
                    placeholder="例如：{title} | {siteTitle}"
                    class="form-input w-full"
                  >
                </div>
                
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    Meta 描述模板
                  </label>
                  <textarea
                    v-model="advancedSeoForm.metaTemplates.article.description"
                    class="form-input w-full min-h-[80px]"
                  ></textarea>
                </div>
              </div>
            </div>
            
            <!-- 分类页模板 -->
            <div class="p-4 bg-gray-50 rounded-md border border-gray-200">
              <h4 class="font-medium text-gray-800 mb-3">分类页</h4>
              
              <div class="space-y-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    Meta 标题模板
                  </label>
                  <input
                    type="text"
                    v-model="advancedSeoForm.metaTemplates.category.title"
                    placeholder="例如：{category} | {siteTitle}"
                    class="form-input w-full"
                  >
                </div>
                
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    Meta 描述模板
                  </label>
                  <textarea
                    v-model="advancedSeoForm.metaTemplates.category.description"
                    class="form-input w-full min-h-[80px]"
                  ></textarea>
                </div>
              </div>
            </div>
            
            <!-- 可用变量说明 -->
            <div class="mt-6 p-3 bg-blue-50 rounded-md border border-blue-100">
              <h4 class="font-medium text-blue-800 mb-2">可用变量</h4>
              <ul class="text-sm text-blue-700 space-y-1">
                <li><code>{siteTitle}</code> - 网站主标题</li>
                <li><code>{siteSubtitle}</code> - 网站副标题</li>
                <li><code>{title}</code> - 页面标题</li>
                <li><code>{category}</code> - 分类名称</li>
                <li><code>{author}</code> - 作者名称</li>
                <li><code>{date}</code> - 发布日期</li>
                <li><code>{excerpt}</code> - 内容摘要</li>
              </ul>
            </div>
          </div>
        </div>
        
        <!-- 链接优化 -->
        <div v-if="activeTab === 'link-optimization'">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">链接优化</h3>
          <p class="text-sm text-gray-600 mb-6">
            配置网站链接相关的SEO设置，包括canonical URL、内部链接优化等。
          </p>
          
          <div class="space-y-6">
            <!-- Canonical URL 设置 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">
                默认Canonical URL 处理
              </label>
              <select
                v-model="advancedSeoForm.linkOptimization.canonicalHandling"
                class="form-input w-full"
              >
                <option value="self">自动使用当前页面URL</option>
                <option value="home">统一指向首页</option>
                <option value="custom">自定义规则</option>
              </select>
            </div>
            
            <!-- 自定义Canonical规则 -->
            <div v-if="advancedSeoForm.linkOptimization.canonicalHandling === 'custom'">
              <label class="block text-sm font-medium text-gray-700 mb-1">
                自定义Canonical规则
              </label>
              <textarea
                v-model="advancedSeoForm.linkOptimization.canonicalRules"
                placeholder="例如：/blog/* → /articles/*"
                class="form-input w-full min-h-[80px] font-mono text-sm"
              ></textarea>
              <p class="mt-1 text-xs text-gray-500">
                每行一条规则，使用通配符*匹配任意字符
              </p>
            </div>
            
            <!-- 内部链接自动添加rel="nofollow" -->
            <div>
              <label class="inline-flex items-center">
                <input
                  type="checkbox"
                  v-model="advancedSeoForm.linkOptimization.autoNofollow"
                  class="text-primary focus:ring-primary"
                >
                <span class="ml-2 text-sm font-medium text-gray-700">
                  自动为外部链接添加 rel="nofollow" 属性
                </span>
              </label>
            </div>
            
            <!-- 链接 Juice 控制 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">
                链接权重控制（Link Juice）
              </label>
              <textarea
                v-model="advancedSeoForm.linkOptimization.linkJuiceExclusions"
                placeholder="/tag/*&#10;/category/*"
                class="form-input w-full min-h-[80px] font-mono text-sm"
              ></textarea>
              <p class="mt-1 text-xs text-gray-500">
                列出不需要传递权重的URL模式，每行一个
              </p>
            </div>
          </div>
        </div>
        
        <!-- 爬虫控制 -->
        <div v-if="activeTab === 'crawl-control'">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">爬虫控制</h3>
          <p class="text-sm text-gray-600 mb-6">
            配置搜索引擎爬虫的访问规则和频率，避免服务器负载过高。
          </p>
          
          <div class="space-y-6">
            <!-- 爬虫速率限制 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">
                爬虫速率限制
              </label>
              <select
                v-model="advancedSeoForm.crawlControl.rateLimit"
                class="form-input w-full"
              >
                <option value="unlimited">无限制</option>
                <option value="slow">慢速 (每10秒1个请求)</option>
                <option value="medium">中速 (每5秒1个请求)</option>
                <option value="fast">快速 (每2秒1个请求)</option>
                <option value="custom">自定义</option>
              </select>
            </div>
            
            <!-- 自定义爬虫速率 -->
            <div v-if="advancedSeoForm.crawlControl.rateLimit === 'custom'">
              <div class="flex items-center gap-2">
                <input
                  type="number"
                  v-model="advancedSeoForm.crawlControl.customDelay"
                  min="1"
                  class="form-input w-24"
                >
                <span class="text-gray-700">秒/请求</span>
              </div>
            </div>
            
            <!-- 禁止爬虫访问的时段 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">
                禁止爬虫访问的时段
              </label>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="text-xs text-gray-500 mb-1 block">开始时间</label>
                  <input
                    type="time"
                    v-model="advancedSeoForm.crawlControl.blockStartTime"
                    class="form-input w-full"
                  >
                </div>
                <div>
                  <label class="text-xs text-gray-500 mb-1 block">结束时间</label>
                  <input
                    type="time"
                    v-model="advancedSeoForm.crawlControl.blockEndTime"
                    class="form-input w-full"
                  >
                </div>
              </div>
              <p class="mt-1 text-xs text-gray-500">
                通常设置在网站访问高峰期，减轻服务器负载
              </p>
            </div>
            
            <!-- 站点地图设置 -->
            <div class="p-4 bg-gray-50 rounded-md border border-gray-200">
              <h4 class="font-medium text-gray-800 mb-3">站点地图 (Sitemap)</h4>
              
              <div class="space-y-4">
                <div>
                  <label class="inline-flex items-center">
                    <input
                      type="checkbox"
                      v-model="advancedSeoForm.crawlControl.sitemap.enabled"
                      class="text-primary focus:ring-primary"
                    >
                    <span class="ml-2 text-sm font-medium text-gray-700">
                      自动生成站点地图
                    </span>
                  </label>
                </div>
                
                <div v-if="advancedSeoForm.crawlControl.sitemap.enabled">
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    站点地图包含内容
                  </label>
                  <div class="space-y-2 pl-2">
                    <label class="inline-flex items-center">
                      <input
                        type="checkbox"
                        v-model="advancedSeoForm.crawlControl.sitemap.includePosts"
                        class="text-primary focus:ring-primary"
                      >
                      <span class="ml-2 text-sm text-gray-700">文章/产品</span>
                    </label>
                    <label class="inline-flex items-center">
                      <input
                        type="checkbox"
                        v-model="advancedSeoForm.crawlControl.sitemap.includePages"
                        class="text-primary focus:ring-primary"
                      >
                      <span class="ml-2 text-sm text-gray-700">页面</span>
                    </label>
                    <label class="inline-flex items-center">
                      <input
                        type="checkbox"
                        v-model="advancedSeoForm.crawlControl.sitemap.includeCategories"
                        class="text-primary focus:ring-primary"
                      >
                      <span class="ml-2 text-sm text-gray-700">分类</span>
                    </label>
                  </div>
                </div>
                
                <div v-if="advancedSeoForm.crawlControl.sitemap.enabled">
                  <label class="block text-sm font-medium text-gray-700 mb-1">
                    站点地图URL
                  </label>
                  <div class="flex">
                    <input
                      type="text"
                      v-model="advancedSeoForm.crawlControl.sitemap.url"
                      class="form-input flex-1 bg-gray-100"
                      readonly
                    >
                    <button 
                      type="button"
                      class="btn btn-secondary ml-2"
                      @click="handleRegenerateSitemap"
                      :loading="regeneratingSitemap"
                    >
                      <i v-if="regeneratingSitemap" class="fa fa-spinner fa-spin mr-1"></i>
                      重新生成
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 成功提示对话框 -->
    <FormDataDetailDialog
      :visible="showSuccessDialog"
      title="操作成功"
      :data="{ message: '高级SEO设置已成功保存' }"
      :fields="[{ label: '提示信息', name: 'message', type: 'text' }]"
      @close="showSuccessDialog = false"
    />
    
    <!-- 确认对话框 -->
    <ConfirmDialog
      :visible="showDiscardConfirm"
      title="放弃更改"
      message="您有未保存的更改，确定要放弃吗？"
      @confirm="handleDiscardChanges"
      @cancel="showDiscardConfirm = false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import FormDataDetailDialog from '@/components/FormDataDetailDialog.vue'
import ConfirmDialog from '@/components/ConfirmDialog.vue'
import { useRouter } from 'vue-router'
import { getAdvancedSeoSettings, saveAdvancedSeoSettings, regenerateSitemap } from '@/api/seo'

// 路由实例
const router = useRouter()

// 选项卡配置
const tabs = [
  { id: 'structured-data', name: '结构化数据' },
  { id: 'meta-templates', name: '元标签模板' },
  { id: 'link-optimization', name: '链接优化' },
  { id: 'crawl-control', name: '爬虫控制' }
]

// 状态变量
const activeTab = ref('structured-data')
const saving = ref(false)
const regeneratingSitemap = ref(false)
const showSuccessDialog = ref(false)
const showDiscardConfirm = ref(false)
const originalData = ref({})
const hasChanges = ref(false)

// 表单数据
const advancedSeoForm = reactive({
  // 结构化数据设置
  structuredData: {
    enabled: true,
    siteType: 'Website',
    organization: {
      name: '',
      logo: '',
      phone: '',
      email: ''
    }
  },
  
  // 元标签模板
  metaTemplates: {
    home: {
      title: '{siteTitle} - 首页',
      description: ''
    },
    article: {
      title: '{title} | {siteTitle}',
      description: '{excerpt}'
    },
    category: {
      title: '{category} | {siteTitle}',
      description: '浏览 {category} 分类下的所有内容'
    }
  },
  
  // 链接优化
  linkOptimization: {
    canonicalHandling: 'self',
    canonicalRules: '',
    autoNofollow: true,
    linkJuiceExclusions: '/tag/*\n/category/*'
  },
  
  // 爬虫控制
  crawlControl: {
    rateLimit: 'medium',
    customDelay: 5,
    blockStartTime: '09:00',
    blockEndTime: '18:00',
    sitemap: {
      enabled: true,
      includePosts: true,
      includePages: true,
      includeCategories: true,
      url: '/sitemap.xml'
    }
  }
})

// 结构化数据预览
const structuredDataPreview = computed(() => {
  if (!advancedSeoForm.structuredData.enabled) return '请启用结构化数据以查看预览'
  
  let schema = {
    '@context': 'https://schema.org',
    '@type': advancedSeoForm.structuredData.siteType
  }
  
  if (advancedSeoForm.structuredData.siteType === 'Organization') {
    schema.name = advancedSeoForm.structuredData.organization.name || '示例组织名称'
    if (advancedSeoForm.structuredData.organization.logo) {
      schema.logo = advancedSeoForm.structuredData.organization.logo
    }
    if (advancedSeoForm.structuredData.organization.phone) {
      schema.telephone = advancedSeoForm.structuredData.organization.phone
    }
    if (advancedSeoForm.structuredData.organization.email) {
      schema.email = advancedSeoForm.structuredData.organization.email
    }
  } else if (advancedSeoForm.structuredData.siteType === 'Blog') {
    schema.name = '示例博客名称'
    schema.description = '示例博客描述'
    schema.publisher = {
      '@type': 'Organization',
      name: '发布者名称'
    }
  }
  
  return JSON.stringify(schema, null, 2)
})

// 初始化数据
onMounted(async () => {
  try {
    const response = await getAdvancedSeoSettings()
    if (response.data) {
      Object.assign(advancedSeoForm, response.data)
      // 保存原始数据用于检测变化
      originalData.value = JSON.parse(JSON.stringify(response.data))
    }
  } catch (error) {
    console.error('获取高级SEO设置失败:', error)
  }
})

// 监听表单变化
watch(
  () => advancedSeoForm,
  (newVal) => {
    // 比较当前数据与原始数据是否有变化
    hasChanges.value = JSON.stringify(newVal) !== JSON.stringify(originalData.value)
  },
  { deep: true }
)

// 保存设置
const handleSave = async () => {
  saving.value = true
  try {
    await saveAdvancedSeoSettings(advancedSeoForm)
    originalData.value = JSON.parse(JSON.stringify(advancedSeoForm))
    showSuccessDialog.value = true
  } catch (error) {
    console.error('保存高级SEO设置失败:', error)
    alert('保存失败: ' + (error.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

// 重新生成站点地图
const handleRegenerateSitemap = async () => {
  regeneratingSitemap.value = true
  try {
    await regenerateSitemap()
    alert('站点地图已成功重新生成')
  } catch (error) {
    console.error('重新生成站点地图失败:', error)
    alert('生成失败: ' + (error.message || '未知错误'))
  } finally {
    regeneratingSitemap.value = false
  }
}

// 放弃更改
const handleDiscardChanges = () => {
  Object.assign(advancedSeoForm, originalData.value)
  showDiscardConfirm.value = false
}

// 监听路由变化，有未保存的更改时提示
router.beforeEach((to, from, next) => {
  if (hasChanges.value && from.path === router.currentRoute.value.path) {
    showDiscardConfirm.value = true
    // 暂时存储导航目标，在确认后执行
    router.to = to
    next(false)
  } else {
    next()
  }
})

// 确认放弃后继续导航
watch(
  () => showDiscardConfirm.value,
  (newVal) => {
    if (!newVal && router.to) {
      router.push(router.to)
      router.to = null
    }
  }
)
</script>
    